<?php

namespace src\common;

use Medoo\Medoo;
use PDO;
use PDOStatement;

class Db
{
    private static $config;

    private static $instance = [];

    private $medoo;

    public function __construct(Medoo $medoo)
    {
        $this->medoo = $medoo;
    }

    private static function getConfig(): array
    {
        if (self::$config) {
            return self::$config;
        } else {
            if (!file_exists(CONFIG_DIR . 'Db.conf.php')) throw new \Exception('数据库配置文件不存在');
            return self::$config = require_once(CONFIG_DIR . 'Db.conf.php');
        }
    }

    private static function connect(string $dbName): Medoo
    {
        $config = self::getConfig()[$dbName] ?? [];
        if (!$config) throw new \Exception('数据库配置错误');

        $Db = new Medoo($config);
        return $Db;
    }

    public static function db(string $dbName): Db
    {
        if (!isset(self::$instance[$dbName])) {
            self::$instance[$dbName] = new Db(self::connect($dbName));
        }

        return self::$instance[$dbName];
    }

    public function findOne(string $sql): array
    {
        return $this->medoo->exec($sql)->fetch(PDO::FETCH_ASSOC);
    }

    public function findAll(string $sql): array
    {
        return $this->medoo->exec($sql)->fetchAll(PDO::FETCH_ASSOC);
    }

    public function exec(string $sql)
    {
        return $this->medoo->pdo->exec($sql);
    }

    public function rawQuery(string $sql): ?PDOStatement
    {
        return $this->medoo->query($sql);
    }
}
